<template>
  <div class="same-europe-168-page">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>历史同赔查询</span>
          <el-button 
            type="text" 
            @click="toggleSearch"
            :icon="isSearchCollapsed ? 'ArrowDown' : 'ArrowUp'"
          >
            {{ isSearchCollapsed ? '展开' : '收起' }}
          </el-button>
        </div>
      </template>
      
      <el-collapse-transition>
        <div v-show="!isSearchCollapsed">
          <el-form 
            :model="searchForm" 
            :inline="true" 
            class="search-form"
            label-width="100px"
          >
            <!-- 基本信息 -->
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="赛事名称">
                  <el-input 
                    v-model="searchForm.event_name" 
                    placeholder="请输入赛事名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="赛事编号">
                  <el-input 
                    v-model="searchForm.order_num" 
                    placeholder="请输入赛事编号"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="主队名称">
                  <el-input 
                    v-model="searchForm.homesxname" 
                    placeholder="请输入主队名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客队名称">
                  <el-input 
                    v-model="searchForm.awaysxname" 
                    placeholder="请输入客队名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 时间范围 -->
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="所属日期范围">
                  <el-date-picker
                    v-model="ownerdateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="比赛时间范围">
                  <el-date-picker
                    v-model="matchtimeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 显示赔率开关 -->
            <el-row>
              <el-col :span="24" style="text-align: center">
                <el-checkbox v-model="showOdds" label="显示赔率" size="large" />
              </el-col>
            </el-row>
            
            <!-- 操作按钮 -->
            <el-row>
              <el-col :span="24" style="text-align: center">
                <el-button type="primary" @click="handleSearch" :loading="historicalSameOddsLoading">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>查询结果</span>
          <span class="total-info" v-if="historicalSameOddsTotal > 0">
            共 {{ historicalSameOddsTotal }} 条记录
          </span>
        </div>
      </template>

      <el-table 
        :data="historicalSameOddsData" 
        v-loading="historicalSameOddsLoading"
        stripe
        style="width: 100%"
        height="600"
      >
        <el-table-column prop="fid" label="ID" min-width="60" width="100" />
        <el-table-column prop="season_id" label="赛季id" min-width="80" />
        <el-table-column prop="event_name" label="赛事名称" min-width="80" />
        <el-table-column prop="order_num" label="赛事编号" min-width="80" />
        <el-table-column prop="ownerdate" label="所属日期" min-width="90" />
        <el-table-column prop="matchtime" label="比赛时间" min-width="90" />
        <el-table-column prop="homesxname" label="主队" min-width="80" />
        <el-table-column prop="awaysxname" label="客队" min-width="80" />
        <el-table-column prop="homescore" label="主分" min-width="60"  />
        <el-table-column prop="awayscore" label="客分" min-width="60"  />
        <el-table-column prop="home_avg_points" label="主积分" min-width="70" />
        <el-table-column prop="away_avg_points" label="客积分" min-width="70"  />
        
        <!-- 初始赔率 -->
        <el-table-column label="初始赔率" min-width="100" v-if="showOdds">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ row.home_initial || '-' }}</span>
              <span class="odds-item draw">{{ row.draw_initial || '-' }}</span>
              <span class="odds-item away">{{ row.away_initial || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 终赔率 -->
        <el-table-column label="临场赔率" min-width="100" v-if="showOdds">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ row.home_final || '-' }}</span>
              <span class="odds-item draw">{{ row.draw_final || '-' }}</span>
              <span class="odds-item away">{{ row.away_final || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 初始概率 -->
        <el-table-column label="初始概率" min-width="150" v-if="showOdds">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ (row?.prob_home_initial * 100)?.toFixed(2) || '0.00' }}%</span>
              <span class="odds-item draw">{{ (row?.prob_draw_initial * 100)?.toFixed(2) || '0.00' }}%</span>
              <span class="odds-item away">{{ (row?.prob_away_initial * 100)?.toFixed(2) || '0.00' }}%</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 72小时赔率 -->
        <el-table-column label="临场概率" min-width="150" v-if="showOdds">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ (row?.prob_home_final * 100)?.toFixed(2) || '0.00' }}%</span>
              <span class="odds-item draw">{{ (row?.prob_draw_final * 100)?.toFixed(2) || '0.00' }}%</span>
              <span class="odds-item away">{{ (row?.prob_away_final * 100)?.toFixed(2) || '0.00' }}%</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 167小时赔率 -->
        <el-table-column label="返还率" min-width="150" v-if="showOdds">
          <template #default="{ row }">
            <div class="odds-group">
              <span class="odds-item home">{{ (row?.return_rate_initial * 100)?.toFixed(2) || '0.00' }}%</span>
             <span class="odds-item home">{{ (row?.return_rate_final * 100)?.toFixed(2) || '0.00' }}%</span>
              
            </div>
          </template>
        </el-table-column>
        
        <!-- 操作 -->
        <el-table-column label="操作" min-width="100" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="openSameOddsTab(row)"
            >
              同赔分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="historicalSameOddsTotal > 0">
        <el-pagination
          :current-page="historicalSameOddsCurrentPage"
          :page-size="historicalSameOddsSearchCondition.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="historicalSameOddsTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useMatchPredictStore } from '@/pinia/stores/matchPredictStore'
import type { HistoricalSameOddsCondition, HistoricalSameOddsData, SameOdds168AnalysisStats } from './apis/type'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const matchPredictStore = useMatchPredictStore()

// 使用 storeToRefs 保持响应式
const { 
  historicalSameOddsLoading,
  historicalSameOddsData,
  historicalSameOddsPagination,
  historicalSameOddsSearchCondition,
  historicalSameOddsTotal,
  historicalSameOddsCurrentPage
} = storeToRefs(matchPredictStore)

// 响应式数据
const isSearchCollapsed = ref(false)
const ownerdateRange = ref<[string, string] | null>(null)
const matchtimeRange = ref<[string, string] | null>(null)
const showOdds = ref(true) // 是否显示赔率


// 搜索表单
const searchForm = reactive<HistoricalSameOddsCondition>({
  current_page: 1,
  page_size: 20
})

// 方法
function toggleSearch() {
  isSearchCollapsed.value = !isSearchCollapsed.value
}

async function handleSearch() {
  // 处理时间范围
  if (ownerdateRange.value) {
    searchForm.ownerdate_s = ownerdateRange.value[0]
    searchForm.ownerdate_e = ownerdateRange.value[1]
  } else {
    searchForm.ownerdate_s = null
    searchForm.ownerdate_e = null
  }

  if (matchtimeRange.value) {
    searchForm.matchtime_s = matchtimeRange.value[0]
    searchForm.matchtime_e = matchtimeRange.value[1]
  } else {
    searchForm.matchtime_s = null
    searchForm.matchtime_e = null
  }

  // 更新搜索条件并查询
  matchPredictStore.updateHistoricalSameOddsSearchCondition(searchForm)
}

function handleReset() {
  // 重置表单
  const keys = Object.keys(searchForm) as Array<keyof HistoricalSameOddsCondition>
  keys.forEach(key => {
    if (key === 'current_page' || key === 'page_size') {
      searchForm[key] = key === 'current_page' ? 1 : 20
    } else {
      searchForm[key] = null
    }
  })
  
  ownerdateRange.value = null
  matchtimeRange.value = null
  
  // 重置store
  matchPredictStore.resetHistoricalSameOddsSearchCondition()
}

async function handleSizeChange(size: number) {
  matchPredictStore.updateHistoricalSameOddsSearchCondition({
    page_size: size,
    current_page: 1
  })
}

async function handleCurrentChange(page: number) {
  matchPredictStore.updateHistoricalSameOddsSearchCondition({
    current_page: page
  })
}

  // 打开同赔分析页面
  function openSameOddsTab(row: HistoricalSameOddsData) {
    // 将比赛数据设置到store中
    matchPredictStore.setCurrentMatchForAnalysis(row)
    
    // 构建查询参数
    const queryParams = new URLSearchParams({
      fid: row.fid?.toString() || '',
      event_name: row.event_name || '',
      homesxname: row.homesxname || '',
      awaysxname: row.awaysxname || '',
      matchtime: row.matchtime || '',
      homescore: row.homescore?.toString() || '',
      awayscore: row.awayscore?.toString() || '',
      home_initial: row.home_initial?.toString() || '',
      draw_initial: row.draw_initial?.toString() || '',
      away_initial: row.away_initial?.toString() || '',
      home_final: row.home_final?.toString() || '',
      draw_final: row.draw_final?.toString() || '',
      away_final: row.away_final?.toString() || '',
      prob_home_initial: row.prob_home_initial?.toString() || '',
      prob_draw_initial: row.prob_draw_initial?.toString() || '',
      prob_away_initial: row.prob_away_initial?.toString() || '',
      prob_home_final: row.prob_home_final?.toString() || '',
      prob_draw_final: row.prob_draw_final?.toString() || '',
      prob_away_final: row.prob_away_final?.toString() || '',
      return_rate_initial: row.return_rate_initial?.toString() || '',
      return_rate_final: row.return_rate_final?.toString() || '',
      
      // 爆冷分析需要的参数
      season_id: row.season_id?.toString() || '',
      homeid: row.homeid?.toString() || '',
      awayid: row.awayid?.toString() || '',
      order_num: row.order_num || '',
      ownerdate: row.ownerdate || '',
      home_avg_points: row.home_avg_points?.toString() || '',
      away_avg_points: row.away_avg_points?.toString() || ''
    })
    
    // 使用 Vue Router 导航到同赔分析页面，通过URL参数传递数据
    router.push(`/odds/same-odds-analysis?${queryParams.toString()}`)
  }


// 生命周期
onMounted(() => {
  // 初始查询
  matchPredictStore.fetchHistoricalSameOdds()
})
</script>

<style scoped>
.same-europe-168-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #909399;
  font-size: 14px;
}

.search-form {
  padding: 20px 0;
}

.odds-group {
  display: flex;
  gap: 2px;
}

.odds-item {
  padding: 2px 2px;
  border-radius: 2px;
  font-size: 12px;
  font-weight: bold;
}

.odds-item.home {
  background-color: #f0f9ff;
  color: #1e40af;
}

.odds-item.draw {
  background-color: #fef3c7;
  color: #92400e;
}

.odds-item.away {
  background-color: #f0fdf4;
  color: #166534;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}


.el-divider {
  margin: 20px 0;
}
</style>
